package com.saxon.file;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Random;
import java.util.UUID;

public class fileUpLoad extends HttpServlet {

    @Override
    protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //判断文件是不是有文件上传的项
        if (! ServletFileUpload.isMultipartContent (req)) {
            return;//终止方法,没有文件上传的功能
        }
        //创建文件上传的路径 建议在WEB-INF目录下因为外部无法直接访问，比较安全；
        String realPath = this.getServletContext ().getRealPath ("/WEB-INF/load");
        File file = new File (realPath);
        if (! file.exists ()) {
            boolean mkdir = file.mkdir ();
        }
        //临时文件区域，当文件的大小超过了一定的大小，就放在这里，超过一定的时间九自动删除；
        String tempPath = this.getServletContext ().getRealPath ("/WEB-INF/temp");
        File temp = new File (tempPath);
        if (! temp.exists ()) {
            boolean mkdir = temp.mkdir ();
        }
        //获得一个工厂
        /*
          @see DiskFileItemFactory
         * public static final int DEFAULT_SIZE_THRESHOLD = 10240;
         *     private File repository; 存储库文件的地方
         *     private int sizeThreshold;  文件的大小
         *     private FileCleaningTracker fileCleaningTracker;清理文件
         *     private String defaultCharset;编码
         *      public static final String DEFAULT_CHARSET = "ISO-8859-1";
         */
        DiskFileItemFactory factory = new DiskFileItemFactory ();
        //factory要有。
        ServletFileUpload Upload = new ServletFileUpload (factory);
        //监听我们的进程的进度
        Upload.setProgressListener (new ProgressListener () {
            /**
             * @param pBytesRead 已经读取的文件
             * @param pContentLength 文件上传的大小
             * @param pItems 已经上传的项目
             */
            @Override
            public void update (long pBytesRead, long pContentLength, int pItems) {
            }
        });
        //获得文件的后缀和文件的名字

        //解析前端的请求，封装成一个fileitem对象
        List<FileItem> list = null;
        try {
            list = Upload.parseRequest (req);
            for (FileItem fileItem : list) {
                if (fileItem.isFormField ()) {

                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace ();
        }
    }

    @Override
    protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet (req, resp);
    }
}
